package com.wms.ymcc.mq;

import com.alibaba.fastjson.JSONObject;
import com.wms.ymcc.constant.ValidationConstants;
import com.wms.ymcc.domain.MessageSms;
import com.wms.ymcc.dto.MessageSmsDto;
import com.wms.ymcc.dto.User2PhoneDto;
import com.wms.ymcc.exception.GlobalBaseException;
import com.wms.ymcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @author : 阿盛哟
 * @description :
 * @createDate : 2025/6/20 20:28
 */
@RocketMQMessageListener(topic = ValidationConstants.ROCKETMQ_TOPIC_PUBLISH,
        selectorExpression = ValidationConstants.ROCKETMQ_TAGS_SMS,
        consumerGroup = "service-common-consumer-sms")
@Service
@Slf4j
public class MQConsumerSmsService implements RocketMQListener<MessageExt> {


    @Autowired
    private IMessageSmsService iMessageSmsService;

    /**
     * 消费
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1. 获取到消息
        try {
            String jsonStrMessage = new String(messageExt.getBody(), "UTF-8");
            MessageSmsDto messageSmsDto = JSONObject.parseObject(jsonStrMessage, MessageSmsDto.class);
            // 2. 存到 t_message_sms
            List<User2PhoneDto> user2PhoneDtos = messageSmsDto.getUser2PhoneDtos();

            user2PhoneDtos.stream().forEach(up -> {
                MessageSms messageSms = new MessageSms();
                BeanUtils.copyProperties(messageSmsDto,messageSms);
                messageSms.setSendTime(new Date());
                messageSms.setPhone(up.getPhone());
                messageSms.setUserId(up.getUserId());
                iMessageSmsService.insert(messageSms);
            });

            // 发送短信。。。。。。。  略
            log.info("短信推送消息消费结果成功");

        } catch (UnsupportedEncodingException e) {
            throw new GlobalBaseException("短息推送消息消费失败");
        }


    }
}